package com.lovo.shirodemo.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.shirodemo.result.ResultCode;
import com.lovo.shirodemo.result.ResultVO;
import com.lovo.shirodemo.util.WebUtil;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ObjectInputValidation;
import java.io.PrintWriter;

public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (this.isLoginRequest(request, response)) {
            if (this.isLoginSubmission(request, response)) {

                return this.executeLogin(request, response);
            } else {

                return true;
            }
        } else {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse resp = (HttpServletResponse) response;
            if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
                resp.setStatus(HttpStatus.OK.value());
                return true;
            } else {
                /**
                 * 在这里实现自己想返回的信息，其他地方和源码一样就可以了
                 */
                WebUtil.writeJson(ResultVO.fail(ResultCode.USER_AUTHENTICATION_ERROR),resp);
                return false;
            }
        }
    }
}
